/* Copyright (c) 2008 Charles Rich and Worcester Polytechnic Institute.
 * All Rights Reserved.  Use is subject to license terms.  See the file
 * "license.terms" for information on usage and redistribution of this
 * file and for a DISCLAIMER OF ALL WARRANTIES.
 */
package edu.wpi.cetask;

import edu.wpi.cetask.Description.Taskable;

import org.w3c.dom.*;

import java.util.*;

import javax.xml.xpath.XPathConstants;

public class TaskModel extends Description {
   
   TaskModel (Node node, TaskEngine engine) { 
      super(node, engine);
   }
   
   public TaskClass getTaskClass (String id) {
      return getTaskClass((Node) 
            xpath("./task[@id=\""+id+"\"]", XPathConstants.NODE), this);
   }

   public List<Script> getScripts () {
      List<Script> scripts = new ArrayList<Script>();
      for (Node node : xpathNodes("./script"))
         scripts.add(getScript(node, null));
      return scripts;
   }
   
   @Override
   public String toString () { return getNamespace(); }
   
   private final Properties properties = new Properties(engine.properties);
   
   public static class Error extends RuntimeException {
      public Error (Description description, String error) { 
         super(description+": "+error);
      }
   }
   
   /**
    * Base class for members of task model with id's
    */
   abstract class Member extends Description {
      
      // TODO jing does not appear to check for duplicate id's

      protected Member (Node node) { super(node, TaskModel.this.engine); }
      
      public String getId () { return xpath("./@id"); }
      
      public TaskModel getModel () { return TaskModel.this; }
      
      public String getProperty (String key) {
         return properties.getProperty(getId()+key);
      }
      
      public void setProperty (String key, String value) {
         properties.setProperty(getId()+key, value);
      }
   
      @Override
      public boolean equals (Object object) {
         return object instanceof Member && ((Member) object).node == node;
      }
      
      @Override
      public int hashCode () { return node.hashCode(); }
      
      @Override
      public String toString () { 
         // for readability, suppress namespace for last loaded task model
         return getNamespace().equals(TaskEngine.getNamespace()) ? getId() :
            getNamespace()+'#'+getId(); 
      }
   }
  
}
